import { 
	ApiSaveCart,
	ApiGetCartCount,
	ApiGetCartList,
	ApiRemoveByCartIds,
	ApiUpdateCartNum,
	ApiRemoveCart,
	ApiSubmitCarts,
	ApiUpdateCartCheck,
	ApiGetCartCouponList,
	ApiGetCartCoupon
 } from '@/common/request/api/cart.js'
import { ApiGetAllActivity } from '@/common/request/api/activity.js'
import {
	CARTCOUNT,
	CARTDATA,
	SETTOTALPRICEANDCOUNT,
	CHECKALL,
	CHECKCART,
	UPDATECARTNUM,
	SHOP_CARTACTIVITYLIST,
	CARTACTCOUPONLIST,
	CARTACTUSECOUPON
} from "../types.js"

const state = {
	cartUseCoupon:{},
	cartCount:0, // 购物车数量
	cartData:{
		check:false,// 购物车是否全选
		cartActivityList:[]
	}, // 购物车数据
	loadingStatus:'loading',
	goodsTotalPrice:0, // 购物车结算金额
	checkNum:0, // 选中的购物车数量
	dePrice:0, // 购物车优惠金额
	nowActivityMonList:[],
	nowActivityList:[],
	willActivityList:[],
	nowShopActivity:{},
	willShopActivity:{},
	shopCartActivityList:[],
	cartCouponList:{
		receiveCouponList:[],
		receivedCouponList:[]
	}// 购物车优惠券列表
}
const actions = {
	// 获取全部店铺活动
	async ActGetAllCartActivity({commit,dispatch},payload){
		const res = await ApiGetAllActivity(payload)
		if(res.success){
			if(payload.isCoupon){
			}else{
				commit('SHOP_CARTACTIVITYLIST', res.data)
			}
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
		return res
	},
	// 获取购物车优惠券列表
	async ActGetCartCouponList({commit,dispatch},payload){
		const res = await ApiGetCartCouponList(payload)
		if(res.success){
			commit('CARTACTCOUPONLIST',res.data)
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
		return res
	},
	// 获取购物车使用优惠券
	async ActGetCartCoupon({commit,dispatch},payload){
		const res = await ApiGetCartCoupon(payload)
		if(res.success){
			commit('CARTACTUSECOUPON',res.data)
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
		return res
	},
	// 获取购物车数量
	async ActGetCartCount({commit,},payload){
		const res = await ApiGetCartCount(payload)
		if(res.success){
			if(!payload.goodsId){
				commit('CARTCOUNT',res.data)
			}
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
		return res
	},
	// 加入购物车
	async ActSaveCart({commit,dispatch},payload){
		const res = await ApiSaveCart(payload)
		if(res.success){
			dispatch('ActGetCartCount',{storeId:uni.getStorageSync('storeId')})
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
		return res
	},
	// 删除购物车
	async ActRemoveByCartIds({commit,dispatch},payload){
		const res = await ApiRemoveByCartIds(payload)
		if(res.success){
			dispatch('ActGetCartCount')
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
	},
	// 获取购物车列表
	async ActGetCartList({commit},payload){
		const res = await ApiGetCartList({...payload,time:new Date().getTime()})
		if(res.success){
			commit('CARTDATA',res.data)
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
	},
	// 修改购物车选中状态
	async ActUpdateCartCheck({dispatch},payload){
		const res = await ApiUpdateCartCheck(payload)
		if(res.success){
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
	},
	// 修改购物车数量
	async ActUpdateCartNum({dispatch},payload){
		const res = await ApiUpdateCartNum(payload)
		if(res.success){
			await dispatch('ActGetCartCoupon',{
				storeId:uni.getStorageSync('storeId')
			})
			dispatch('ActGetCartCount')
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
	},
	// 清空购物车
	async ActRemoveCart({dispatch},payload){
		const res = await ApiRemoveCart(payload)
		if(res.success){
			await dispatch('ActGetCartCoupon',{
				storeId:uni.getStorageSync('storeId')
			})
			dispatch('ActGetCartCount',{storeId:uni.getStorageSync('storeId')})
			dispatch('ActGetCartList',{storeId:uni.getStorageSync('storeId')})
			
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
		return res
	},
	// 提交购物车
	async ActSubmitCarts({commit,},payload){
		uni.showLoading({
			mask:true,
			title:'提交中'
		})
		const res = await ApiSubmitCarts(payload)
		uni.hideLoading()
		if(res.success){
			if(res.data.useCouponVO && res.data.useCouponVO.useCouponList && res.data.useCouponVO.useCouponList.length > 0){
				res.data.useCouponVO.useCouponList.push({
					id:'',
					activity:{
						activityName:'不使用优惠券'
					},
					activityRule:{
						couponAmount:0
					}
				})
			}
			uni.setStorageSync('order',res.data)
			uni.navigateTo({
				url:'/pages/order/order'
			})
		}else{
			uni.showModal({
				title: '提示',
				content: res.msg,
				showCancel:false
			});
		}
		return res
	},
}
const mutations ={
	[CARTACTCOUPONLIST](state, data){
		state.cartCouponList = data
	},
	[CARTACTUSECOUPON](state, data){
		state.cartUseCoupon = data
	},
	// 购物车数量
	[CARTCOUNT](state, data){
		state.cartCount = data
	},
	// 购物车全选
	[CHECKALL](state,data){
		state.cartData.cartActivityList.map((cartActItem,cartActIndex)=>{
			cartActItem.check = data
			cartActItem.cartList.map((cartItem,cartIndex)=>{
				cartItem.check = data
			})
		})
		this.commit('SETTOTALPRICEANDCOUNT',data)
	},
	// 购物车单个商品选择
	[CHECKCART](state,data){
		state.cartData.cartActivityList.map((cartActItem,cartActIndex)=>{
			cartActItem.check = false
			cartActItem.cartList.map((cartItem,cartIndex)=>{
				if(cartItem.cartId === data.name){
					cartItem.check = data.value
				}
				if(cartItem.check){
					cartActItem.check = true
				}
			})
		})
		this.commit('SETTOTALPRICEANDCOUNT')
	},
	// 购物车列表
	[CARTDATA](state, data){
		state.cartData = data
		this.commit('SETTOTALPRICEANDCOUNT',data)
	},
	// 购物车全场活动列表
	[SHOP_CARTACTIVITYLIST](state, data){
		state.shopCartActivityList = data
	},
	// 修改购物车数量
	[UPDATECARTNUM](state, data){
		data.map((dataItem,dataIndex)=>{
			// 修改购物车中购物车数量
			state.cartData.cartActivityList.map((cartActItem,cartActIndex)=>{
				cartActItem.cartList.map((cartItem,cartIndex)=>{
					if(cartItem.goodsId == dataItem.goodsId){
						if(dataItem.num==0){
							cartActItem.cartList.splice(cartIndex,1)
						}else{
							cartItem.goodsNum=dataItem.num
						}
						return
					}
				})
			})
		})
		this.commit('SETTOTALPRICEANDCOUNT')
	},
	// 计算购物车价格和数量
	[SETTOTALPRICEANDCOUNT](state, data){
		let goodsTotalPrice = 0
		let checkNum = 0
		let dePrice = 0
		let allChecked = true
		let nowActivityList = []; // 已满足的活动规则列表
		let willActivityList = []; // 即将满足的活动规则列表
		let nowActivity = {}; // 已满足的活动规则
		let willActivity = {}; // 即将满足的活动规则
		let nowShopActivity = {}; // 已满足的店铺活动规则
		let willShopActivity = {}; // 即将满足的店铺活动规则
		let dePriceItem = 0 // 当前活动优惠金额
		let nowActivityMon = 0; // 当前活动下选中的商品金额或数量
		let nowActivityMonList = []; // 当前活动下选中的商品金额或数量
		state.cartData.cartActivityList.map((cartActItem,cartActIndex)=>{
			if(cartActItem.activity.activityType == 10){
				let showDescription = ''
				cartActItem.activity.activityRuleList.map((v,i)=>{
					showDescription += `满${v.limitWhere}元，立减${v.couponAmount}元；`
				})
				cartActItem.showDescription = showDescription
				dePriceItem = 0;
				nowActivityMon = 0;
				nowActivity = {};
				willActivity = {};
				cartActItem.cartList.map((cartItem,cartIndex)=>{
					if(cartItem.check){
						checkNum += Number(cartItem.goodsNum)
						goodsTotalPrice += Number(cartItem.goodsPrice)*Number(cartItem.goodsNum)
						nowActivityMon += Number(cartItem.goodsPrice)*Number(cartItem.goodsNum)
						cartActItem.check = true
					}else{
						allChecked = false
					}
				})
				willActivity = cartActItem.activity.activityRuleList.find(
					(v, i, a) => {
						if (nowActivityMon < Number(v.limitWhere)) {
							return true;
						}
					},
				);
				cartActItem.activity.activityRuleList.reverse();
				nowActivity = cartActItem.activity.activityRuleList.find(
					v => {
						if (nowActivityMon >= Number(v.limitWhere)) {
							dePriceItem = parseFloat(v.couponAmount || 0);
							return true;
						}
					},
				);
				cartActItem.activity.activityRuleList.reverse();
				nowActivityMonList[cartActIndex] = nowActivityMon;
				nowActivityList[cartActIndex] = nowActivity;
				willActivityList[cartActIndex] = willActivity;
				dePrice += parseFloat(dePriceItem);
			}else if(cartActItem.activity.activityType == 30){
				let showDescription = ''
				cartActItem.activity.activityRuleList.map((v,i)=>{
					showDescription += `${v.ruleName}；`
				})
				cartActItem.showDescription = showDescription
				nowActivityMon = 0;
				nowActivity = {};
				willActivity = {};
				cartActItem.cartList.map((cartItem,cartIndex)=>{
					if(cartItem.check){
						checkNum += Number(cartItem.goodsNum)
						goodsTotalPrice += Number(cartItem.goodsPrice)*Number(cartItem.goodsNum)
						nowActivityMon += Number(cartItem.goodsPrice)*Number(cartItem.goodsNum)
						cartActItem.check = true
					}else{
						allChecked = false
					}
				})
				willActivity = cartActItem.activity.activityRuleList.find(
					(v, i, a) => {
						console.log(nowActivityMon < Number(v.limitWhere))
						if (nowActivityMon < Number(v.limitWhere)) {
							return true;
						}
					},
				);
				cartActItem.activity.activityRuleList.reverse();
				nowActivity = cartActItem.activity.activityRuleList.find(
					v => {
						if (nowActivityMon >= Number(v.limitWhere)) {
							return true;
						}
					},
				);
				cartActItem.activity.activityRuleList.reverse();
				nowActivityMonList[cartActIndex] = nowActivityMon;
				nowActivityList[cartActIndex] = nowActivity;
				willActivityList[cartActIndex] = willActivity;
			}else{
				cartActItem.cartList.map((cartItem,cartIndex)=>{
					if(cartItem.check){
						checkNum += Number(cartItem.goodsNum)
						goodsTotalPrice += Number(cartItem.goodsPrice)*Number(cartItem.goodsNum)
						cartActItem.check = true
					}else{
						allChecked = false
					}
				})
			}
		})
		console.log(state.shopCartActivityList)
		if(state.shopCartActivityList.length > 0){
			if(state.shopCartActivityList[0].activityType == 10){
				willShopActivity = state.shopCartActivityList[0].activityRuleList.find(
					(v, i, a) => {
						if (goodsTotalPrice < Number(v.limitWhere)) {
							return true;
						}
					},
				);
				state.shopCartActivityList[0].activityRuleList.reverse();
				nowShopActivity = state.shopCartActivityList[0].activityRuleList.find(
					v => {
						if (goodsTotalPrice >= Number(v.limitWhere)) {
							dePrice += parseFloat(v.couponAmount || 0);
							return true;
						}
					},
				);
				state.shopCartActivityList[0].activityRuleList.reverse();
			}
		}
		console.log(nowShopActivity)
		console.log(willShopActivity)
		
		state.goodsTotalPrice = goodsTotalPrice
		state.checkNum = checkNum
		state.dePrice = dePrice
		state.nowActivityMonList = nowActivityMonList
		state.nowActivityList = nowActivityList
		state.willActivityList = willActivityList
		state.nowShopActivity = nowShopActivity
		state.willShopActivity = willShopActivity
		state.cartData.check = allChecked
	},
}
const getters = {
	
}

export default {
	state,
	mutations,
	actions,
	getters
}